import { message } from 'antd';
import { isSuccess } from '@/utils/request';

import { hrOverviewRecheck, salaryRecheck } from '@/services/salaryManage/salaryCalculate';

import TabsMenuRight from '@/pages/SalaryManage/components/TabsMenuRight';
import modelType from '@/pages/SalaryManage/SalaryCalculate/constant/modelTypeConstant';
import ComputeOverviewTable from '@/pages/SalaryManage/SalaryCalculate/Recheck/ComputeOverviewTable';


const { latestSalaryYearMonth } = salaryRecheck;
const { queryPayrollTableBodyData } = hrOverviewRecheck;

function* getState(select, namespace) {
    return yield select(state => state[namespace]);
}

function* searchPostData(select, namespace) {
    const currentState = yield* getState(select, namespace);

    const periodStr = currentState.period || '';
    const year = periodStr.substr(0, 4);
    const month = periodStr.substr(5);
    return {
        year,
        month: month ? String(parseInt(month, 10)) : month,
        actionType: 1,
        requestBusiUnit: 2,
        ...currentState.searchModel
    };
}

function* getTableData(select, namespace) {
    const currentState = yield* getState(select, namespace);
    return {
        dataSource: currentState.dataSource,
        footerSource: currentState.footerSource,
        historySource: currentState.historySource || []
    };
}

const namespace = 'overviewRecheckModel';
const shareNamespace = 'payoffSharedModel';
const overviewRecheckModel = {
    namespace,
    state: {
        period: null,
        checkButtonList: [],
        searchModel: {
            departmentCode: '',
            organizationCode: '',
            encryptAverageAmtLowest: '',
            encryptAverageAmtHighest: '',
            encryptTotalPayAmtLowest: '',
            encryptTotalPayAmtHighest: '',
            encryptTotalTaxAmtLowest: '',
            encryptTotalTaxAmtHighest: ''
        },
        tableLoading: false,
        rowKey: 'deptCode',
        dataSource: [],
        historySource: [],
        footerSource: null
    },
    reducers: {
        [modelType.SET_MULTI_STORE](state, action) {
            return {
                ...state,
                ...action.payload
            };
        },
        [modelType.SET_LOADING](state, action) {
            return {
                ...state,
                ...action.payload
            };
        },
        [modelType.RESET_STORE](state, action) {
            return {
                ...state,
                checkButtonList: [],
                searchModel: {
                    departmentCode: '',
                    encryptTotalPayAmtLowest: '',
                    encryptTotalPayAmtHighest: '',
                    encryptTotalTaxAmtLowest: '',
                    encryptTotalTaxAmtHighest: '',
                    encryptAverageAmtLowest: '',
                    encryptAverageAmtHighest: '',
                    organizationCode: null,
                    ...action.payload
                },
                period: null,
                dataSource: [],
                historySource: [],
                footerSource: null
            };
        },
        /**
         * 更变月份
         * @param action.payload 月份
         */
        [modelType.SET_PERIOD](state, action) {
            const { payload: period } = action;

            return {
                ...state,
                period
            };
        },
        [modelType.INIT_STORE](state) {
            return {
                ...state,
                checkButtonList: [],
                period: null,
                dataSource: [],
                historySource: [],
                footerSource: null
            };
        },
        [modelType.SET_PAGE_INFO](state, action) {
            const {
                overviewList: dataSource = [],
                overviewTotal: footerData = [],
                historySource
            } = action.payload.data;

            const footerSource = footerData || {};
            footerSource.deptName = '合计';

            return {
                ...state,
                dataSource,
                footerSource: [footerSource],
                historySource: historySource || dataSource
            };
        },
        [modelType.SET_SEARCH_CONDITION](state, action) {
            const { searchModel } = state;
            const { payload } = action;
            return {
                ...state,
                searchModel: {
                    ...searchModel,
                    ...payload
                }
            };
        }
    },
    effects: {
        *[modelType.E_INIT](state, { put, call, select, all }) {
            // 如果不是切换月份，则调用接口获取默认年月

            let postData = yield* searchPostData(select, namespace);

            if (!state.payload) {
                const response = yield call(latestSalaryYearMonth, {
                    organizationCode: postData.organizationCode
                });

                if (!isSuccess(response)) {
                    message.error(`请求【当前月份】数据失败：${response.msg}`);
                    return;
                }

                // 未配置月模板，不请求数据
                if (!response.data.year || !response.data.month) {
                    // 设置默认月份
                    yield put({
                        type: modelType.INIT_STORE
                    });
                    yield put({
                        type: `${shareNamespace}/${modelType.E_SHARED_STATE}`,
                        payload: {
                            sharePeriod: null
                        }
                    });
                    return;
                }
                const { year, month } = response.data;

                // 设置默认月份
                yield put({
                    type: modelType.SET_PERIOD,
                    payload: `${year}-${(month < 10 ? '0' : '') + month}`
                });
            } else {
                // 设置默认月份
                yield put({
                    type: modelType.SET_PERIOD,
                    // payload: moment().from(new Date()).format('YYYY-MM')
                    payload: state.payload
                });
            }
            postData = yield* searchPostData(select, namespace);
            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: true }
            });
            const [recordResponse] = yield all([
                // 查询表格表体数据
                call(queryPayrollTableBodyData, postData)
            ]);
            if (isSuccess(recordResponse)) {
                yield put({
                    type: modelType.SET_PAGE_INFO,
                    payload: recordResponse
                });
            } else {
                message.error(`请求表身数据失败：${recordResponse.msg}`);
            }

            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: false }
            });
        },
        *[modelType.E_SEARCH_CONDITION](state, { put }) {
            yield put({
                type: modelType.SET_SEARCH_CONDITION,
                payload: state.payload
            });
            state.callback()
        },
        *[modelType.E_SEARCH](s, { put, select }) {
            //  设置查询条件;
            if (s.payload) {
                yield put({
                    type: modelType.SET_SEARCH_CONDITION,
                    payload: s.payload
                });
            }

            const postData = yield* searchPostData(select, namespace);

            if (!postData.year || !postData.month) {
                message.error('请选择薪资年月');
                return;
            }

            const tableData = yield* getTableData(select, namespace);
            const data = ComputeOverviewTable(tableData.historySource, {
                ...postData,
                ...s.payload
            });

            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: true }
            });

            yield put({
                type: modelType.SET_PAGE_INFO,
                payload: { data }
            });

            yield put({
                type: modelType.SET_LOADING,
                payload: { tableLoading: false }
            });
            // const postData = yield* searchPostData(select, namespace);

            // yield put({
            //     type: modelType.SET_LOADING,
            //     payload: { tableLoading: true }
            // });

            // const [response] = yield all([call(queryTableBodyData, postData)]);

            // if (isSuccess(response)) {
            //     yield put({
            //         type: modelType.SET_PAGE_INFO,
            //         payload: response
            //     });
            // } else {
            //     message.error(`请求表身数据失败：${response.msg}`);
            // }

            // yield put({
            //     type: modelType.SET_LOADING,
            //     payload: { tableLoading: false }
            // });
        },
        // 重置
        *[modelType.E_RESET](state, { put }) {
            yield put({
                type: modelType.RESET_STORE,
                payload: state.payload
            });
        }
    }
};


overviewRecheckModel.state.RecheckMenuRight = TabsMenuRight

export default overviewRecheckModel;
